package com.open.demo.location

import android.annotation.SuppressLint
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationServices.getFusedLocationProviderClient
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.tasks.OnFailureListener
import java.util.*


/**
 *
 * @Author: hailong.qiu hailong.qiu@xgimi.com
 * @Maintainer: hailong.qiu hailong.qiu@xgimi.com
 * @Date: 2021/7/29
 * @Copyright: 2021 www.xgimi.com Inc. All rights reserved.
 */
class GmsLocationActivity: AppCompatActivity() {

    companion object {
        const val TAG = "GMS Location Test"
        private const val UPDATE_INTERVAL = (10 * 1000 /* 10 secs */).toLong()
        private const val FASTEST_INTERVAL: Long = 2000 /* 2 sec */
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startLocationUpdates()
        getLastLocation()
    }

    /**
     * 这个方法可以获取到定位信息
     */
    @SuppressLint("MissingPermission")
    private fun startLocationUpdates() {
        val locationRequest = LocationRequest()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        locationRequest.interval = UPDATE_INTERVAL;
        locationRequest.fastestInterval = FASTEST_INTERVAL;

        // Create LocationSettingsRequest object using location request
        // Create LocationSettingsRequest object using location request
        val builder = LocationSettingsRequest.Builder()
        builder.addLocationRequest(locationRequest)
        val locationSettingsRequest = builder.build()

        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        val settingsClient = LocationServices.getSettingsClient(this)
        settingsClient.checkLocationSettings(locationSettingsRequest)

        // new Google API SDK v11 uses getFusedLocationProviderClient(this)
        // new Google API SDK v11 uses getFusedLocationProviderClient(this)
        getFusedLocationProviderClient(this).requestLocationUpdates(
            locationRequest, object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult) {
                    // do work here
                    onLocationChanged(locationResult.lastLocation)
                }
            },
            Looper.myLooper()
        )
    }

    fun onLocationChanged(location: Location) {
        // New location has now been determined
        val msg = "GMS Updated Location: " +
                java.lang.Double.toString(location.getLatitude()) + "," +
                java.lang.Double.toString(location.getLongitude())
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
        Log.d(TAG, "onLocationChanged ${msg}")
        // 获取定位的相关地址信息
        // val url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=${location.latitude},${location.longitude}&language=zh-CN&sensor=false"
        val geocoder = Geocoder(this, Locale.getDefault())
        val address = geocoder.getFromLocation(location.latitude, location.longitude, 1)
        Log.d(TAG, "onLocationChanged address:${address.first().toString()}")
    }

    @SuppressLint("MissingPermission")
    private fun getLastLocation() {
        // Get last known recent location using new Google Play Services SDK (v11+)
        val locationClient = getFusedLocationProviderClient(this)
        locationClient.lastLocation
            .addOnSuccessListener { location -> // GPS location can be null if GPS is switched off
                Log.d(TAG, "getLastLocation addOnSuccessListener location:${location}")
                location?.let { onLocationChanged(it) }
            }
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    Log.d(TAG, "getLastLocation addOnCompleteListener result:${task.result}")
                } else {
                    Log.d(TAG, "getLastLocation addOnCompleteListener Exception:${task.exception}")
                }
            }
            .addOnFailureListener(object : OnFailureListener {
                override fun onFailure(e: Exception) {
                    Log.d(TAG, "getLastLocation onFailure Error trying to get last GPS location error:${e.message}")
                    e.printStackTrace()
                }
            })
    }

}